package com.whnk.pm.service.impl;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.DocxRenderData;
import com.deepoove.poi.data.PictureRenderData;
import com.whnk.common.config.Global;
import com.whnk.common.constant.ConfigConstants;
import com.whnk.common.utils.file.FileUtils;
import com.whnk.pm.domain.*;
import com.whnk.pm.dto.ResumeDocDTO;
import com.whnk.pm.mapper.*;
import com.whnk.pm.service.IResumeService;
import com.whnk.pm.util.FileUtil;
import com.whnk.pm.util.ValidateException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.jsoup.nodes.Entities.EscapeMode.base;

@Service
public class ResumeServiceImpl implements IResumeService {

    private static final Logger log = LoggerFactory.getLogger(ResumeServiceImpl.class);
    @Autowired
    private BaseInfoMapper baseInfoMapper;
    @Autowired
    private EduInfoMapper eduInfoMapper;
    @Autowired
    private WorkInfoMapper workInfoMapper;
    @Autowired
    private ProjInfoMapper projInfoMapper;
    @Autowired
    private FileInfoMapper fileInfoMapper;
    @Autowired
    private ConfigConstants configConstants;

    @Override
    public String downloadResume(List<String> listStr, List<String> errorMsg) throws Exception {
        final String globalprofile = Global.getDownloadPath();
        /**
         * 从数据库取数据
         */
        List<File> docxFileList = new ArrayList<>();
        for (String empID : listStr) {
            // 基本信息
            BaseInfo baseInfo = baseInfoMapper.selectBaseInfoById(empID);
            // 教育经历
            EduInfo eduInfoSelect = new EduInfo();
            eduInfoSelect.setEmpId(empID);
            List<EduInfo> eduInfoList = eduInfoMapper.selectEduInfoList(eduInfoSelect);
            eduInfoList.sort(Comparator.comparing((k1) -> (
                (k1.getEmpGradDt() == null ? new Date(): k1.getEmpGradDt())
            )));
            // 工作经历
            WorkInfo workInfo = new WorkInfo();
            workInfo.setEmpId(empID);
            List<WorkInfo> workInfoList = workInfoMapper.selectWorkInfoList(workInfo);
            workInfoList.sort(Comparator.comparing((k1) -> (
                    (k1.getEmpWorkEddt() == null ? new Date(): k1.getEmpWorkEddt())
            )));
            // 项目经历
            ProjInfo projInfo = new ProjInfo();
            projInfo.setEmpId(empID);
            List<ProjInfo> projInfoList = projInfoMapper.selectProjInfoList(projInfo);
            projInfoList.sort(Comparator.comparing((k1) -> (
                    (k1.getEmpPjEddt() == null ? new Date(): k1.getEmpPjEddt())
            )));
            // 文件副本
            FileInfo fileInfo = new FileInfo();
            fileInfo.setEmpId(empID);
            List<FileInfo> fileInfoList = fileInfoMapper.selectFileInfoList(fileInfo);
            DateFormat simpleDateFormatEdu = new SimpleDateFormat("yyyy.MM.dd");
            DateFormat simpleDateFormatWrok = new SimpleDateFormat("yyyy.MM");
            ResumeDocDTO resumeDocDTO = new ResumeDocDTO();
            resumeDocDTO.setDate(simpleDateFormatEdu.format(new Date()));
            if (baseInfo != null) {
                //姓名
                resumeDocDTO.setEmpNm(baseInfo.getEmpNm());
                //性别
                resumeDocDTO.setEmpSex(baseInfo.getEmpSex());
                //手机号
                resumeDocDTO.setEmpTel(baseInfo.getEmpTel());
                //证件类型
                resumeDocDTO.setEmpIdTtype(baseInfo.getEmpIdType());
                //证件号
                resumeDocDTO.setEmpId(baseInfo.getEmpId());
                //人员技能及特长
                resumeDocDTO.setEmpSkills(baseInfo.getEmpSkills());
            }
            if (CollectionUtils.isNotEmpty(eduInfoList)) {
                StringBuffer stringBuffer = new StringBuffer();
                for (EduInfo eduInfo: eduInfoList) {
                    stringBuffer.append(simpleDateFormatEdu.format(eduInfo.getEmpEnroDt())).append("-").append(simpleDateFormatEdu.format(eduInfo.getEmpGradDt()))
                            .append("\t").append(eduInfo.getEmpSch()).append("\t").append(eduInfo.getEmpMajor())
                            .append("\t").append(eduInfo.getEmpEdu()).append("\n");
                }
                resumeDocDTO.setEmpEduInfos(stringBuffer.toString());
            }
            if (CollectionUtils.isNotEmpty(workInfoList)) {
                StringBuffer stringBuffer = new StringBuffer();
                for (WorkInfo work : workInfoList) {
                    stringBuffer.append(simpleDateFormatWrok.format(work.getEmpWorkStdt())).append("-").append(work.getEmpWorkEddt()==null?"至今":simpleDateFormatWrok.format(work.getEmpWorkEddt())).append("\t")
                            .append(work.getEmpComp()).append("\t").append(work.getEmpJob()).append("\n");
                }
                resumeDocDTO.setEmpWorkInfos(stringBuffer.toString());
            }
            if (CollectionUtils.isNotEmpty(projInfoList)) {
                StringBuffer stringBuffer = new StringBuffer();
                int i = 1;
                for (ProjInfo project : projInfoList) {
                    int index = i++;
                    stringBuffer.append(index+"、 ").append(simpleDateFormatWrok.format(project.getEmpPjStdt())).append("-").append(project.getEmpPjEddt()==null?"至今":simpleDateFormatWrok.format(project.getEmpPjEddt()))
                            .append("\t").append(project.getEmpComp()).append("\t").append(project.getEmpPjNm()).append("\t")
                            .append(project.getEmpPjType()).append("\t")/*.append(project.getEmpPjRole()).append("\t")*/
                            .append(project.getEmpPjDesc()).append("\n");
                }
                resumeDocDTO.setEmpProjInfos(stringBuffer.toString());
            }
            //插入图片
            setImage(resumeDocDTO,fileInfoList, errorMsg);
            File file = new File(globalprofile + baseInfo.getEmpNm() + "_" + baseInfo.getEmpId() + ".docx");
            if (!file.exists()) {
                file.createNewFile();
            } else {
                file.deleteOnExit();
            }
            try (InputStream inputStream = ResumeServiceImpl.class.getResourceAsStream("/resume-template.docx");
                 OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))) {
                ZipSecureFile.setMinInflateRatio(-1.0d);
                XWPFTemplate template = XWPFTemplate.compile(inputStream).render(resumeDocDTO);
                template.write(outputStream);
            }
            docxFileList.add(file.getAbsoluteFile());
        }
        if (CollectionUtils.isNotEmpty(errorMsg)) {
            throw new ValidateException();
        }
        //压缩zip文档
        LocalDate localDate = LocalDate.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dateStr = localDate.format(dateTimeFormatter);
        File zipFileName = new File(globalprofile + dateStr + ".zip");
        FileUtil.zipFile(zipFileName, docxFileList);
        return zipFileName.getName();
    }

    /**
     * word 插入图片
     * @param resumeDocDTO
     * @param fileInfoList
     */
    private void setImage(ResumeDocDTO resumeDocDTO, List<FileInfo> fileInfoList, List<String> errorMsg) throws IOException {
        //身份证
        List<Map<String, PictureRenderData>> idImgList = new ArrayList<>();
        //毕业证
        List<Map<String, PictureRenderData>> eduImgList = new ArrayList<>();
        //学位证
        List<Map<String, PictureRenderData>> graduateImgList = new ArrayList<>();
        //合同
        List<Map<String, PictureRenderData>> conImgList = new ArrayList<>();
        //社保证明
        List<Map<String, PictureRenderData>> socialImgList = new ArrayList<>();

        for (FileInfo fileInfo1 : fileInfoList) {
            Map<String, PictureRenderData> map = new HashMap<>();
            String attType = fileInfo1.getEmpAttType();
            String filePath = configConstants.getFileBaseDir() + fileInfo1.getEmpFileId();
            File fileResource = new File(filePath);
            byte[] bytes = FileUtils.File2byte(fileResource);

            PictureRenderData pictureRenderData = new PictureRenderData(400, 300,
                    Global.getDownloadPath() + fileInfo1.getEmpFileNm(), bytes);
            if (attType.contains("身份证")) {
                idImgList.add(new HashMap<String, PictureRenderData>() {
                    {
                        {
                            put("picture", pictureRenderData);
                        }
                    }
                });
            } else if (attType.contains("学历证")) {
                eduImgList.add(new HashMap<String, PictureRenderData>() {
                    {
                        {
                            put("picture", pictureRenderData);
                        }
                    }
                });
            } else if (attType.contains("学位证")) {
                graduateImgList.add(new HashMap<String, PictureRenderData>() {
                    {
                        {
                            put("picture", pictureRenderData);
                        }
                    }
                });
            } else if (attType.contains("合同")) {
                conImgList.add(new HashMap<String, PictureRenderData>() {
                    {
                        {
                            put("picture", pictureRenderData);
                        }
                    }
                });
            } else if (attType.contains("社保证明")) {
                socialImgList.add(new HashMap<String, PictureRenderData>() {
                    {
                        {
                            put("picture", pictureRenderData);
                        }
                    }
                });
            }
        }
        //图片校验
        if (CollectionUtils.isEmpty(idImgList) || CollectionUtils.isEmpty(eduImgList) ||
                (CollectionUtils.isEmpty(conImgList) && CollectionUtils.isEmpty(socialImgList))) {
            errorMsg.add(resumeDocDTO.getEmpNm() + resumeDocDTO.getEmpId() + " 身份证、学历证必须上传;合同、社保证明至少有一个上传");
        }

        try(InputStream idsegment = ResumeServiceImpl.class.getResourceAsStream("/segment.docx");
            InputStream edusegment = ResumeServiceImpl.class.getResourceAsStream("/segment.docx");
            InputStream graduatesegment = ResumeServiceImpl.class.getResourceAsStream("/segment.docx");
            InputStream consegment = ResumeServiceImpl.class.getResourceAsStream("/segment.docx");
            InputStream socialsegment = ResumeServiceImpl.class.getResourceAsStream("/segment.docx")){
            //身份证
            if (CollectionUtils.isNotEmpty(idImgList)) {
                DocxRenderData idImg = new DocxRenderData(idsegment, idImgList);
                resumeDocDTO.setEmpIdImg(idImg);
            }
            //毕业证
            if (CollectionUtils.isNotEmpty(eduImgList)) {
                DocxRenderData eduImg = new DocxRenderData(edusegment, eduImgList);
                resumeDocDTO.setEmpEduImg(eduImg);
            }
            //学位证
            if (CollectionUtils.isNotEmpty(graduateImgList)) {
                DocxRenderData graduateImg = new DocxRenderData(graduatesegment, graduateImgList);
                resumeDocDTO.setEmpGraduateImg(graduateImg);
            }
            //合同
            if (CollectionUtils.isNotEmpty(conImgList)) {
                DocxRenderData conImg = new DocxRenderData(consegment, conImgList);
                resumeDocDTO.setEmpConimg(conImg);
            }
            //社保证明
            if (CollectionUtils.isNotEmpty(socialImgList)) {
                DocxRenderData socialImg = new DocxRenderData(socialsegment, socialImgList);
                resumeDocDTO.setEmpSocialImg(socialImg);
            }
        }
    }
}
